package com.android.phoenix.database;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

import com.android.phoenix.models.SportRecord;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class BycecleDataBaseHelper extends OrmLiteSqliteOpenHelper {
	/** 数据库名称 */
	private static final String DATABASE_NAME = "bycecle.db";
	/** 数据库版本，升级使用 */
	private static final int DATABASE_VERSION = 1;

	/** Dao层 */
	private Dao<SportRecord, String> sportRecordDao = null;

	public BycecleDataBaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	public BycecleDataBaseHelper(Context context, String databaseName,
			CursorFactory factory, int databaseVersion) {
		super(context, DATABASE_NAME, factory, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
		try {
			TableUtils.createTable(connectionSource, SportRecord.class);
		} catch (SQLException e) {
			Log.i(BycecleDataBaseHelper.class.getName(),
					"Create database failure!");
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2,
			int arg3) {
		try {
			TableUtils.dropTable(connectionSource, SportRecord.class, true);

			onCreate(arg0, arg1);
		} catch (final SQLException e) {
			Log.i(BycecleDataBaseHelper.class.getName(),
					"Update database failure!");
			e.printStackTrace();
		}
	}

	@Override
	public void close() {
		super.close();
		sportRecordDao = null;
	}

	/** 取得 sportRecordDao 对象 */
	public Dao<SportRecord, String> getSportRecordDao() throws SQLException {
		if (sportRecordDao == null) {
			sportRecordDao = getDao(SportRecord.class);
		}
		return sportRecordDao;
	}

}
